package com.linchong.xshop.service.impl;

import com.linchong.xshop.dao.ShopDao;
import com.linchong.xshop.dto.ImageHolder;
import com.linchong.xshop.dto.ShopExecution;
import com.linchong.xshop.entity.Shop;
import com.linchong.xshop.enums.ShopStateEnum;
import com.linchong.xshop.exceptions.ShopOperationException;
import com.linchong.xshop.service.ShopService;
import com.linchong.xshop.util.ImageUtil;
import com.linchong.xshop.util.PageCalculator;
import com.linchong.xshop.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * @author linchong
 * @desc 店铺相关服务
 * @email littlexbear@163.com
 * @create 2018-07-15 8:47
 * @CopyRight(C) https://blog.csdn.net/littlexbear
 **/
@Service
public class ShopServiceImpl implements ShopService{

    @Autowired
    private ShopDao shopDao;

    @Override
    public ShopExecution getShopList(Shop shopCondition, int pageIndex, int pageSize) {
        int rowIndex = PageCalculator.calculateRowIndex(pageIndex,pageSize);
        List<Shop> shopList = shopDao.queryShopList(shopCondition,rowIndex,pageSize);
        int count = shopDao.queryShopCount(shopCondition);
        ShopExecution se = new ShopExecution();
        if(shopList != null){
            se.setShopList(shopList);
            se.setCount(count);
        }else {
            se.setState(ShopStateEnum.INNER_ERROR.getState());
        }
        return se;
    }

    @Override
    public Shop getByShopId(long shopId) {
        return shopDao.queryByShopId(shopId);
    }

    @Override
    public ShopExecution modifyShop(Shop shop,  ImageHolder thumbnail) throws ShopOperationException {

          if(shop==null||shop.getShopId()==null){
              return new ShopExecution(ShopStateEnum.NULL_SHOP);
          }else{
              //1.判断是否要处理图片信息
              try {
                  if (thumbnail.getImage() != null && thumbnail.getImageName() != null && !"".equals(thumbnail.getImageName())) {
                      Shop tempShop = shopDao.queryByShopId(shop.getShopId());
                      //删除店铺原有的图片信息
                      if (tempShop.getShopImg() != null) {
                          ImageUtil.deleteFileOrPath(tempShop.getShopImg());
                      }
                      //生成新的图片
                      addShopImg(shop, thumbnail);


                  }

                  //2.更新店铺信息
                  shop.setLastEditTime(new Date());
                  int effectedNum = shopDao.updateShop(shop);
                  if (effectedNum <= 0) {
                      return new ShopExecution(ShopStateEnum.INNER_ERROR);
                  } else {
                      //获取最新的店铺信息，返回前台
                      shop = shopDao.queryByShopId(shop.getShopId());
                      return new ShopExecution(ShopStateEnum.SUCCESS, shop);
                  }
              }catch (Exception e){
                  throw new ShopOperationException("modifyShop error"+e.getMessage());
              }
          }



    }

    @Override
    @Transactional
    public ShopExecution addShop(Shop shop,  ImageHolder thumbnail) {
        //判断店铺是否为空
        if(shop == null){
            return new ShopExecution(ShopStateEnum.NULL_SHOP);
        }
        //判断其他是否为空，例如：商品种类，区域等也需要判断
        //添加店铺操作
        /**
         * 初始化必要参数：是否上架，是否已经审核
         * 1.向数据库中添加一条店铺信息
         * 2.存储处理图片
         * 3.更新数据库中店铺信息(图片地址)
         */
        try{
            //给店铺信息赋初始值
            shop.setEnableStatus(0);
            shop.setCreateTime(new Date());
            shop.setLastEditTime(new Date());
            //添加店铺信息
            int effectedNum = shopDao.insertShop(shop); //步骤1
            if(effectedNum<=0){
                //采用RuntimeException时抛出异常，事务才会回滚。
                throw new ShopOperationException("店铺创建失败！"); //插入失败，
            }else{
                if(thumbnail.getImage() !=null){
                    try {
                        addShopImg(shop, thumbnail);//步骤2，店铺+文件流
                    }catch (Exception e){
                        //图片存储失败，事务终止，回滚
                        throw new ShopOperationException("addShopImg error:"+e.getMessage());
                    }
                    //更新图片的地址
                    effectedNum = shopDao.updateShop(shop);
                    if(effectedNum<=0){
                        throw new ShopOperationException("更新图片地址失败！");
                    }
                }
            }
        }catch (Exception e){
            throw new ShopOperationException("addShop error:"+e.getMessage());
        }
        return new ShopExecution(ShopStateEnum.CHENCK,shop);
    }

    /**
     * 添加店铺图片
     * @param shop
     * @param shopImgInputStream
     */
    private void addShopImg(Shop shop, ImageHolder thumbnail) {
        //获取shop图片目录的相对值路径
        String dest = PathUtil.getShopImagePath(shop.getShopId());
        String shopImgAddr = ImageUtil.generateThumbnail(thumbnail,dest);
        shop.setShopImg(shopImgAddr);
    }
}
